<p>In the context of ASP.NET Core MVC web applications, both model binding and model validation are processes that take place prior to the execution
of a controller action. It is imperative for the application to examine the <code>ModelState.IsValid</code> and respond accordingly.</p>
<p>This rule enforces the developer to validate the model within a controller action, ensuring the application’s robustness and reliability.</p>
<h2>Why is this an issue?</h2>
<p>Querying the <code>ModelState.IsValid</code> property is necessary because it checks if the submitted data in the HTTP request is valid or not.
This property evaluates all the validation attributes applied on your model properties and determines whether the data provided satisfies those
validation rules.</p>
<h3>What is the potential impact?</h3>
<p>Skipping model validation can lead to:</p>
<ul>
  <li> Data Integrity Issues: Without validation, incorrect or inconsistent data can be saved to your database, leading to potential data corruption
  or loss. </li>
  <li> Security Vulnerabilities: Skipping validation can expose your application to security risks because incoming user data isn’t properly checked.
  For example, any <a href="https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-9.0#built-in-attributes">validation
  attributes</a>] applied to your model properties, will be ignored. This lack of proper input validation could lead to various injection attacks,
  like SQL injection, cross-site scripting and others. </li>
  <li> Application Errors: Invalid data can lead to unexpected application errors or crashes, which can disrupt the user experience and potentially
  lead to data loss. </li>
  <li> Poor User Experience: Without validation, users may not receive appropriate feedback about any mistakes in the data they have entered, leading
  to confusion and frustration. </li>
  <li> Increased Debugging Time: If invalid data causes issues in your application and was not validatated at the entry point, it can take
  significantly more time to debug and fix these issues. </li>
</ul>
<p>Therefore, it’s highly recommended to always validate models in your application to ensure data integrity, application stability, and a good user
experience.</p>
<p>While client-side validation enhances user experience by providing immediate feedback, it’s not sufficient due to potential manipulation of
client-side code, browser compatibility issues, and dependence on JavaScript. Users can bypass or disable it, leading to invalid or malicious data
being submitted. Therefore, server-side validation is essential to ensure data integrity and security, making it a best practice to use both
client-side and server-side validation in your application.</p>
<h3>Exceptions</h3>
<ul>
  <li> Web API controllers don’t have to check <code>ModelState.IsValid</code> if they have the <code>[ApiController]</code> attribute. In that case,
  an automatic HTTP <code>400</code> response containing error details is returned when model state is invalid. </li>
  <li> When action filters are used for controller actions, the analyzer will skip the model validation detection to avoid false positives since the
  model state could be verified by the action filer. </li>
  <li> <code>TryValidateModel</code> can also be used for model validation. </li>
  <li> The project references a 3rd-party library for validation, e.g. FluentValidation. </li>
  <li> The rule will not raise issues if the model, or the model members, are not decorated with validation attributes, or if it does not implement
  custom validation. </li>
</ul>
<h2>How to fix it</h2>
<p>If <code>ModelState.IsValid</code> returns true, it means that the data is valid and the process can continue. If it returns false, it means that
the validation failed, indicating that the data is not in the expected format or is missing required information.</p>
<p>In such cases, the controller action should handle this by returning an appropriate response, such as re-displaying the form with error messages.
This helps maintain the integrity of the data and provides feedback to the user, enhancing the overall user experience and security of your
application.</p>
<h3>Code examples</h3>
<h4>Noncompliant code example</h4>
<pre data-diff-id="1" data-diff-type="noncompliant">
public async Task&lt;IActionResult&gt; Create(Movie movie) // Noncompliant: model validity check is missing
{
    _context.Movies.Add(movie);
    await _context.SaveChangesAsync();

    return RedirectToAction(nameof(Index));
}
</pre>
<h4>Compliant solution</h4>
<pre data-diff-id="1" data-diff-type="compliant">
public async Task&lt;IActionResult&gt; Create(Movie movie)
{
    if (!ModelState.IsValid)
    {
        return View(movie);
    }

    _context.Movies.Add(movie);
    await _context.SaveChangesAsync();

    return RedirectToAction(nameof(Index));
}
</pre>
<h2>Resources</h2>
<h3>Documentation</h3>
<ul>
  <li> Microsoft Learn - <a href="https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation">Model Validation</a> </li>
  <li> Microsoft Learn - <a
  href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.modelbinding.modelstatedictionary.isvalid">IsValid property</a> </li>
  <li> Microsoft Learn - <a
  href="https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.validationattribute">ValidationAttribute</a> </li>
  <li> Fluent Validation - <a href="https://docs.fluentvalidation.net/en/latest/aspnet.html">ASP.NET Core integration</a> </li>
</ul>

